package com.springcloud.zuul.config;

import org.springframework.cloud.netflix.zuul.filters.Route;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: springcloud-zuul
 * @description: swagger文档资源配置类 （重点swagger整合zuul配置）
 * @author: zhlu
 * @create: 2019-12-28 15:23
 * @Introduction(说明背景故事)
 **/
@Component
@Primary
public class DocumentationConfig implements SwaggerResourcesProvider {

    private final RouteLocator routeLocator;

    public DocumentationConfig(RouteLocator routeLocator) {
        this.routeLocator = routeLocator;
    }

    /**
     * Description: 自动获取系统配置的路由资源集合
     * @author zhlu
     * @date 2019/12/28 3:28 下午
     * @param
     * @return java.util.List<springfox.documentation.swagger.web.SwaggerResource>
     */
    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> resources = new ArrayList<>();
        List<Route> routes = routeLocator.getRoutes();
        resources.add(swaggerResource("权限网关", "/v2/api-docs", "1.0"));
        routes.forEach(route ->
                resources.add(swaggerResource(route.getId(), route.getFullPath().replace("/**", "/v2/api-docs"),"1.0")));
        return resources;
    }

    private SwaggerResource swaggerResource(String name, String location, String version) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion(version);
        return swaggerResource;
    }
}
